'''

    View Factory Test


'''

from PyQt4 import QtGui, QtOpenGL, QtCore, Qt

_REGISTRY ={
    "Browser":      (("Main", "Files"), None),
    "Jobs":         (("Main", "Utils"), None),
    "Properties":   (("Main", "Editors"), None),
}

def register(type, groups, func):
    '''
    Add a view creation callback.
    
    Any previously registered view with the same type
    will be lost.
    
    Use the groups parameter to group types in menus.
    
    The func parameter must be callable with two parameters:
        the name, the view parent
    It must return the created widget.
    
    See also the registerable() decorator
    '''
    global _REGITRY
    _REGISTRY[type] = (groups,func)

def registerable(type, groups):
    '''
    Decorator to turn a function into a view creator:
        
        @VIEW_CREATE("TypeName", ("group",))
        def _create_a_view(self, type, parent):
            retrun MyView(parent)
    
    '''
    def registerer(func):
        register(type, groups, func)
        return func
    return registerer

def types():
    return _REGISTRY.keys()

def types_by_group():
    ret = {}
    for type, (groups,creator) in _REGISTRY.iteritems():
        for group in groups:
            if group not in ret:
                ret[group] = []
            ret[group].append( type )
    return ret
    
class _ViewCreateAction( QtGui.QAction ):
    def __init__( self, viewType, owner, setTypeFunc ):
        QtGui.QAction.__init__( self, viewType, owner )
        self.viewType = viewType
        self.setTypeFunc = setTypeFunc
        
    def trigger( self ):
        self.setTypeFunc( self.viewType )

def create_menu(owner, setTypeFunc):
    menu = QtGui.QMenu(owner)
    for group, types in types_by_group().iteritems():
        grpMenu = menu.addMenu( group )
        for t in types:
            action = _ViewCreateAction(t,owner,setTypeFunc)
            grpMenu.addAction( action )
            owner.connect(
                action, QtCore.SIGNAL( "triggered()" ),
                action.trigger
            )
    return menu

def create(type, parent):
    '''
    Creates a view of the given type under the given 
    parent and returns it.
    '''
    groups, createFunc = _REGISTRY.get(type, ((),lambda t,p:None))
    if createFunc is not None:
        return createFunc(type, parent)
    
    w = None
    if type == 'Browser':
        w = QtGui.QLabel( type, parent )
    elif type == 'Jobs':
        w = QtGui.QLabel( type, parent )
    elif type == 'Properties':
        w = QtGui.QLabel( type, parent )
    else:
        w = QtGui.QLabel( "???", parent )
    return w

